/*
 * Copyright 2007 - The JDPF Project Team (http://www.jdpf.org) 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package org.jdpf.plugins.histogram.serializer.file.histogramcsvserializer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.jdpf.core.kernel.elements.Token;
import org.jdpf.core.plugins.blocks.AbstractSerializerPlugin;
import org.jdpf.core.plugins.datatypes.AbstractDataType;
import org.jdpf.core.plugins.exceptions.PluginException;
import org.jdpf.core.plugins.exceptions.PluginExceptionsEnum;
import org.jdpf.plugins.datatypes.media.Histogram;

/**This block can serialize the Histogram data type to a csv file.
 * 
 * @author Bruno Farina
 * @version 1.0.0
 */
public class HistogramSerializer extends AbstractSerializerPlugin {

	private static final String FILE_EXTENSION = ".csv";

	private String _outputFileName;			//Optional
	private String _outputDirectory;		//Mandatory

	/**Default construtor
	 * @param transitionId - the unique ID for the transition in the net
	 * @param transitionName - the name for the transition
	 */
	public HistogramSerializer(String transitionId, String transitionName) {
		super(transitionId, transitionName);
	}

	/**Process an Histogram data type to get a .csv file.
	 * <p>The algorithm read all data wrapped in the Histogram and then it writes 
	 * the to a text file following CSV spefications (see 
	 * <a href="http://www.rfc-editor.org/rfc/rfc4180.txt">RFC 4180</a>).<br>
	 * The output file contains the three histograms, one for each component (RGB),
	 * separated by an empty line.<br>
	 * Each value of the histogram is reported as:
	 * <br><br><code>
	 * 	color_level;# of pixels for this level
	 * </code><br><br>
	 * For example:
	 * <br><br><code>
	 * 	125;1538<br>
	 * 	126;2567<br>
	 * 	ecc.<br>
	 * </code><br><br>
	 * <p>
	 * 
	 * @see org.jdpf.core.plugins.blocks.AbstractTransitionPlugin#process(java.util.List)
	 */
	@Override
	public Token process(List<Token> list) throws PluginException {
		File dir = new File(_outputDirectory);
		if (dir.exists() && dir.isFile()) {
			throw new PluginException(
					PluginExceptionsEnum.ExecutionError,
					this.getPluginId(),
					"The path reported in parameter "
							+ "OutputDirectory correspind to a file. Unable to end processing.");
		} else if (!dir.exists())
			dir.mkdir();
		List<AbstractDataType> inList = list.get(0).getValueList();
		double tot = inList.size() * 3.0;
		for (int z = 0; z < inList.size() && start; z++) {
			Histogram hist = (Histogram) inList.get(z);
			String fileName = hist.getImageName();
			if (_outputFileName != null)
				fileName = _outputFileName + z;
			fileName += FILE_EXTENSION;
			File f = new File(dir.getAbsolutePath()
					+ System.getProperty("file.separator") + fileName);
			try {
				FileWriter fw = new FileWriter(f);
				List<double[]> value = (List<double[]>) hist.getValue();
				for (int w = 0; w < value.size() && start; w++) {
					double[] channel = value.get(w);
					for (int j = 0; j < channel.length && start; j++) {
						fw.write(j + ";" + channel[j] + "\r\n");
					}
					fw.write("\r\n");
					percentage = Math.min(100.0,(z + 1) * (w + 1) / tot * 100);
				}
				fw.close();
				this.log(this, this.getPluginId(), this.getId(),
						"The histogram for the image " + hist.getImageName()
								+ " successfully saved if file "
								+ f.getAbsoluteFile());

			} catch (IOException e) {
				this.error(this, this.getPluginId(), this.getId(),
						"Unable to write the output file " + fileName + " :\n"
								+ e.getMessage());
			}
		}
		return new Token();
	}

	/**Set the output directory path where the block has to write the .csv file.
	 * @param outputDirecotry - the absolute path of the otput directory.
	 */
	public void setOutputDirectory(String outputDirecotry) {
		_outputDirectory = outputDirecotry;
	}

	/**Set the name for the output file.
	 * <p>Since the <code>OutputFileName</code> parameter fo this block is optional
	 * it can be <code>null</code>. <br>If it is so the block uses as defualt file name
	 * the image name the Histogram data type keeps.</p>
	 * @param fileName - the name for the output csv file.
	 */
	public void setOutputFileName(String fileName) {
		_outputFileName = fileName;
	}

}
